package com.example.popmp3.activity;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.os.Handler;

import com.example.popmp3.R;
import com.example.popmp3.dao.MusicListDAO;
import com.example.popmp3.dao.SingleListDAO;
import com.example.popmp3.model.Tb_musiclist;
import com.example.popmp3.model.Tb_singlelist;

/**
 * Created by Administrator on 2016/3/4.
 */
public class PlayMusic extends Activity implements OnClickListener {
    ImageButton play, pre, next;
    SeekBar seekBar;
    int mSeekStatus = 0;
    private Handler mHandler;
    private MediaPlayer mediaPlayer;
    String strid, idType;
    String loveid = "";
    TextView textView, nowPlayTime, allTime;
    private int currentID = 1; // 当前播放歌曲的索引
    private boolean ifplay = false;
    private boolean iffirst = false;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private boolean isChanging = false;//互斥变量，防止定时器与SeekBar拖动时进度冲突
    Intent intent = null, intent2 = null;
    Bundle bundle = null;
    String[] strInfos;
    int[] single = null;
    MusicListDAO musicListDAO = new MusicListDAO(PlayMusic.this);// 创建FlagDAO对象
    SingleListDAO singleListDAO = new SingleListDAO(PlayMusic.this);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playmusic);
        textView = (TextView) findViewById(R.id.songName);
        play = (ImageButton) findViewById(R.id.play);
        pre = (ImageButton) findViewById(R.id.pre);
        next = (ImageButton) findViewById(R.id.next);
        seekBar = (SeekBar) findViewById(R.id.seekBar1);
        nowPlayTime = (TextView) findViewById(R.id.textView1);
        allTime = (TextView) findViewById(R.id.textView2);
        mediaPlayer = new MediaPlayer();

        intent = getIntent();// 创建Intent对象
        bundle = intent.getExtras();// 获取传入的数据，并使用Bundle记录
        strInfos = bundle.getStringArray("id");// 将id转换为字符串
        strid = strInfos[0];// 记录id
        idType = strInfos[1];// 记录类型
        textView.setText(musicListDAO.find(Integer.parseInt(strid)).getName());
        playMusic(musicListDAO.find(Integer.parseInt(strid)).getPath());
        currentID = Integer.parseInt(strid);

        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                int dest = seekBar.getProgress();
                int mMax = mediaPlayer.getDuration();
                int sMax = seekBar.getMax();
                mediaPlayer.seekTo(mMax * dest / sMax);
                nowPlayTime.setText(ShowTime(mMax * dest / sMax));

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                nextMusic(); // 播放下一首
            }
        });
        // 为“播放\暂停”按钮添加单击事件监听器
        play.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause(); // 暂停视频的播放
                } else {
                    mediaPlayer.start();    //继续播放
                }
            }
        });
        // 为“下一首”按钮添加单击事件监听器
        next.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                nextMusic(); // 播放下一首
            }
        });
        // 为“上一首”按钮添加单击事件监听器
        pre.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                preMusic(); // 播放上一首
            }
        });
    }

    void playMusic(String path) {
        try {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop(); // 停止当前音频的播放
            }
            mediaPlayer.reset(); // 重置MediaPlayer
            mediaPlayer.setDataSource(path); // 指定要播放的音频文件
            mediaPlayer.prepare(); // 预加载音频文件
            mediaPlayer.start(); // 播放音频
            play.setEnabled(true); // 设置“暂停”按钮可用

            int Alltime = mediaPlayer.getDuration();

            allTime.setText(ShowTime(Alltime));
            startProgressUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 下一首
     void nextMusic() {
            if (currentID >= musicListDAO.getMaxId()) {// 当对currentItem进行+1操作后，如果其值大于等于音频文件的总数
                currentID = 1;
            } else {
                ++currentID; // currentItem的值设置为音频文件总数+1
            }
            textView.setText(musicListDAO.find(currentID).getName());
            playMusic(musicListDAO.find(currentID).getPath()); // 调用playMusic()方法播放音乐
    }

    // 上一首
    void preMusic() {
        if (currentID > 1) {
                --currentID;
        } else {
            currentID = musicListDAO.getMaxId() ;
        }
        textView.setText(musicListDAO.find(currentID).getName());
        playMusic(musicListDAO.find(currentID).getPath()); // 调用playMusic()方法播放音乐
    }

    @Override
    protected void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop(); // 停止音乐的播放
        }
        mediaPlayer.release(); // 释放资源
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
    }
        public void startProgressUpdate(){//开辟Thread 用于定期刷新SeekBar
            DelayThread dThread = new DelayThread(0);
            dThread.start();
        }
        private Handler mHandle = new Handler(){
            @Override
            public void handleMessage(Message msg){
                int position = mediaPlayer.getCurrentPosition();
                int mMax = mediaPlayer.getDuration();
                int sMax = seekBar.getMax();
                seekBar.setProgress(position*sMax/mMax);

            }
        };
        public class DelayThread extends Thread {
            int milliseconds;
            public DelayThread(int i){
                milliseconds = i;
            }
            public void run() {
                while(true){
                    try {
                        sleep(milliseconds);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mHandle.sendEmptyMessage(0);
                }
            }
        }

    //时间显示函数,我们获得音乐信息的是以毫秒为单位的，把把转换成我们熟悉的00:00格式
    public String ShowTime(int time) {
        time /= 1000;
        int minute = time / 60;
        int hour = minute / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }
}
